package cn.jgrzj.kaola.api.util;

import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class APIUtil {
    private static Logger logger = Logger.getLogger("APIUtil");

    public static String createSign(String secretKey, TreeMap<String, String> parameterMap) {
        String sign = secretKey;

        Iterator<Map.Entry<String, String>> it = parameterMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            if (!((String) entry.getKey()).equals("sign")) {
                sign = sign + (String) entry.getKey() + (String) entry.getValue();
            }
        }

        sign = sign + secretKey;
        System.out.println(sign);
        try {
            sign = md5Encode2UpperCase(sign);
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
        return sign;
    }

    public static String md5Encode2UpperCase(String sign)
            throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            logger.log(Level.SEVERE, e.getMessage());
            return "";
        }
        byte[] byteArray = sign.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = md5Bytes[i] & 0xFF;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        String rs = hexValue.toString().toUpperCase();
        return rs;
    }
}
